AsgDetalleRenovacion = function(){
	return {
		rendererVencimiento: function(value){
			var tooltip = "";
			if(value == "1"){
				value = "bullet_red.png";
				tooltip = "POLIZA VENCIDA";
			}else if(value == "2"){
				value = "bullet_orange.png";
				tooltip = "POLIZA VENCE EL DIA DE HOY";
			}else if(value == "3"){
				value = "bullet_yellow.png";
				tooltip = "PROXIMA A VENCER, 15 DIAS O MENOS";
			}else if(value == "4"){
				value = "bullet_green.png";
				tooltip = "NORMAL";
			}
			return "<img src=\"" + Asg.constants.CONTEXT_PATH + "/resources/images/" + value + "\" data-qtip=\"" + tooltip + "\" />";
		},
		cancelar: function(btn){
			if(btn == "no") return;
			var asgPoliza = Asg.Grid.getSelectedRow("asgDetalleRenovacionGrid");
			Asg.Message.progress("Guardarndo Informaci\u00F3n...");
			Ext.Ajax.request({
				timeout: Asg.constants.TIMEOUT_SECONDS,
				url: Asg.constants.CONTEXT_PATH + "/renovaciones/cancelar",
				params: {
					asgPolizaId: AsgSeguros.getAsgPolizaId()
				},
				callback: function(options, success, response){
					Ext.Msg.hide();
					var jsonObject = Asg.Utils.ajaxRequestGetJson(response);
					if(!success || !jsonObject){
						Asg.Message.alertInvalid(Asg.constants.DEFAULT_ERROR_MESSAGE);
						return
					}
					Asg.Message.alert(jsonObject.message || Asg.constants.DEFAULT_ERROR_MESSAGE);
					if(jsonObject.success){
						Ext.getCmp("asgDetalleRenovacionGrid").getStore().load();
					}
				}
			});
		},
		confirmCancelacion: function(){
			var asgPoliza = Asg.Grid.getSelectedRow("asgDetalleRenovacionGrid");
			if(asgPoliza == null || asgPoliza.length == 0){
				Asg.Message.alertInvalid("Debe seleccionar la poliza a cancelar");
				return;
			}
			Asg.Message.confirm("\u00BFEst\u00E1 seguro que desea cancelar la poliza No. " + asgPoliza.get("asgPolizaNumero") + "?", AsgDetalleRenovacion.cancelar);
		},
		save: function(btn){
			if(btn == "no") return;
			Asg.Message.progress("Guardando Informaci\u00F3n...");
			var asgPoliza = Asg.Grid.getSelectedRow("asgDetalleRenovacionGrid");
			Ext.getCmp("asgPolizaForm").getForm().submit({
				url: Asg.constants.CONTEXT_PATH + "/renovaciones/save",
				timeout: Asg.constants.TIMEOUT_SECONDS,
				params: {
					"asgPoliza.asgCliente.asgClienteId": asgPoliza.get("asgClienteId"),
					"asgPoliza.asgPolizaAnterior": asgPoliza.get("asgPolizaNumero"),
					"asgPolizaIdAnterior": asgPoliza.get("asgPolizaId")
				},
				success: function(form, action){
					Asg.Message.alert(action.result.message);
					if(action.result.success){
						Ext.WindowMgr.get("asgDetalleRenovacionWindow").hide();
						Ext.getCmp("asgDetalleRenovacionGrid").getStore().load();
					}
				},
				failure: Asg.Form.failureProcedure
			});
		},
		confirmRenovacion: function(){
			var asgPoliza = Asg.Grid.getSelectedRow("asgDetalleRenovacionGrid");
			Asg.Message.confirm("\u00BFEst\u00E1 seguro que desea renovar la p\u00F3liza: <br />" +
					"<b>No. P\u00F3liza:</b> " + asgPoliza.get("asgPolizaNumero") + "<br />" +
					"<b>Fecha Renovaci\u00F3n:</b> " + Asg.Utils.parseDate(asgPoliza.get("asgPolizaFechaFinalizacion"), 'd/m/Y') + "<br />",
					AsgDetalleRenovacion.save);
		},
		showWindow: function(config){
			if(!Asg.Grid.hasSelection("asgDetalleRenovacionGrid")){
				Asg.Message.alertInvalid("Debe seleccionar la poliza a renovar");
				return;
			}
			var window = Ext.WindowMgr.get("asgDetalleRenovacionWindow");
			if(window){
				if(!window.isVisible()) window.show();
				return;
			}
			new Ext.Window({
				id: "asgDetalleRenovacionWindow",
				title: Asg.constants.APPLICATION_TITLE,
				modal: true,
				width: 500,
				height: 400,
	        	bodyStyle: "background: #DFE8F6",
	        	listeners: {
	        		show: function(){
	        			var asgPoliza = Asg.Grid.getSelectedRow("asgDetalleRenovacionGrid");
	        			Ext.getCmp("asgPolizaForm").getForm().reset();
	        			Asg.Utils.setValue("asgPolizaNumero", asgPoliza.get("asgPolizaNumero"));
	        			Asg.Utils.setValue("asgPolizaNombreCliente", asgPoliza.get("asgCliente"));
	        			Asg.Utils.setValue("ctgAseguradoraId", asgPoliza.get("asgPolizaAseguradoraId"));
	        			Asg.Utils.setValue("ctgTipoSeguroId", asgPoliza.get("asgPolizaTipoSeguroId"));
	        			Asg.Utils.setValue("ctgAsesorId", asgPoliza.get("asgPolizaAsesorId"));
	        			Asg.Utils.setValue("ctgPlanId", asgPoliza.get("asgPolizaPlanId"));
	        		}
	        	},
	        	layout: "fit",
				items: {
	        		xtype: "form",
    	        	id: "asgPolizaForm",
	        		border: false,
	        		layout: {
    	        		type: "table",
						columns: 4,
						tableAttrs: {
				            style: {width: "450px", "margin-top": "5px;"},
				            align: "center"
						}
    	        	},
    	        	defaults: Asg.Form.defaults({width: 220, colspan: 2}),
    	        	items: [
        	        	{xtype: "label", text: "No. P\u00F3liza:", cls: "x-form-item", colspan: 4},
        	        	{
        	        		xtype: "textfield",
        	        		id: "asgPolizaNumero",
        	        		name: "asgPoliza.asgPolizaNumero",
        	        		allowBlank: false,
        	        		maxLength: 20,
        	        		colspan: 4
        	        		
    	        		},
        	        	{xtype: "label", text: "Nombre del Cliente:", cls: "x-form-item", width: 450, colspan: 4},
        	        	{
    	        			xtype: "textfield",
    	        			id: "asgPolizaNombreCliente",
    	        			allowEnable: false,
    	        			width: 445,
    	        			colspan: 4
    	        		},
    	        		{xtype: "label", text: "Aseguradora:", cls: "x-form-item"},
    	        		{xtype: "label", text: "Tipo Seguro:", cls: "x-form-item"},
    	        		{
        	        		xtype: "combo",
        	        		id: "ctgAseguradoraId",
        	        		name: "asgPoliza.ctgAseguradora.ctgAseguradoraId",
        	        		store: new Ext.data.SimpleStore({
        	        			data: config.ctgAseguradoras || [],
        	        			fields: ["id", "value"]
        	        		}),
        	        		displayField: "value",
        	        		valueField: "id",
        	        		listeners: {
        	        			change: function(){
        	        				var currentValue = this.getValue();
        	        				if(!Ext.isEmpty(currentValue)){
        	        					var data = Asg.Combo.filter(currentValue, config.ctgAsesores, 2);
        	        					Asg.Combo.loadData("ctgAsesorId", data, false);
        	        					if(!Ext.isEmpty(Asg.Utils.getValue("ctgTipoSeguroId"))){
        	        						data = Asg.Combo.filterByParameters([currentValue, Asg.Utils.getValue("ctgTipoSeguroId")], 
        	        								config.ctgPlanes, [2, 3]);
        	        						Asg.Combo.loadData("ctgPlanId", data, false);
        	        					}else Asg.Combo.removeAll("ctgPlanId", false);
        	        				}else if(Ext.isEmpty(this.getValue())){
        	        					Asg.Combo.removeAll("ctgAsesorId", false);
        	        					Asg.Combo.removeAll("ctgPlanId", false);
        	        				}
        	        			}
        	        		},
        	        		allowBlank: false
    	        		},{
        	        		xtype: "combo",
        	        		id: "ctgTipoSeguroId",
        	        		name: "asgPoliza.ctgTipoSeguro.ctgCatalogoId",
        	        		store: new Ext.data.SimpleStore({
        	        			data: config.ctgTipoSeguros || [],
        	        			fields: ["id", "value"]
        	        		}),
        	        		displayField: "value",
        	        		valueField: "id",
        	        		listeners: {
        	        			change: function(){
        	        				var currentValue = this.getValue();
        	        				if(!Ext.isEmpty(currentValue) && !Ext.isEmpty(Asg.Utils.getValue("ctgAseguradoraId"))){
        	        					var data = Asg.Combo.filterByParameters([Asg.Utils.getValue("ctgAseguradoraId"), currentValue], 
					                         config.ctgPlanes, [2, 3]);
        	        					Asg.Combo.loadData("ctgPlanId", data, false);
        	        				}else if(Ext.isEmpty(this.getValue())){
        	        					Asg.Combo.removeAll("ctgPlanId", false);
        	        				}
        	        			}
        	        		},
        	        		allowBlank: false
    	        		},
    	        		{xtype: "label", text: "Plan:", cls: "x-form-item"},
    	        		{xtype: "label", text: "Asesor:", cls: "x-form-item"},
    	        		{
        	        		xtype: "combo",
        	        		id: "ctgPlanId",
        	        		name: "asgPoliza.ctgPlan.ctgPlanId",
        	        		store: new Ext.data.SimpleStore({
        	        			data: [],
        	        			fields: ["id", "value"]
        	        		}),
        	        		displayField: "value",
        	        		valueField: "id",
        	        		allowBlank: false
    	        		},{
        	        		xtype: "combo",
        	        		id:"ctgAsesorId",
        	        		name: "asgPoliza.ctgAsesor.ctgAsesorId",
        	        		store: new Ext.data.SimpleStore({
        	        			data: [],
        	        			fields: ["id", "value"]
        	        		}),
        	        		displayField: "value",
        	        		valueField: "id",
        	        		allowBlank: false
    	        		},
    	        		{xtype: "label", text: "Forma de Pago:", cls: "x-form-item", colspan: 4},
    	        		{
        	        		xtype: "combo",
        	        		name: "asgPoliza.ctgFormaPago.ctgCatalogoId",
        	        		store: new Ext.data.SimpleStore({
        	        			data: config.ctgFormasPago || [],
        	        			fields: ["id", "value"]
        	        		}),
        	        		displayField: "value",
        	        		valueField: "id",
        	        		colspan: 4
    	        		},
    	        		{xtype: "label", text: "Suma Asegurada:", cls: "x-form-item", colspan: 1, width: 105},
    	        		{xtype: "label", text: "Prima Anual:", cls: "x-form-item", colspan: 1, width: 105},
    	        		{xtype: "label", text: "Cuota Inicial:", cls: "x-form-item", colspan: 1, width: 105},
    	        		{xtype: "label", text: "Cant. de Cuotas:", cls: "x-form-item", colspan: 1, width: 105},
    	        		{
    	        			xtype: "numericfield",
    	        			name: "asgPoliza.asgPolizaSumaAsegurada",
    	        			allowZero: false,
    	        			allowBlank: false,
    	        			maxLength: 20,
    	        			width: 105,
    	        			colspan: 1
    	        		},{
    	        			xtype: "numericfield",
    	        			name: "asgPoliza.asgPolizaPrima",
    	        			allowZero: false,
    	        			allowBlank: false,
    	        			maxLength: 10,
    	        			width: 100,
    	        			colspan: 1
    	        		},{
    	        			xtype: "numericfield",
    	        			name: "asgPoliza.asgPolizaCuotaInicial",
    	        			allowBlank: false,
    	        			maxLength: 10,
    	        			width: 100,
    	        			colspan: 1
    	        		},{
    	        			xtype: "numberfield",
    	        			id: "asgPolizaCantidadCuota",
    	        			name: "asgPoliza.asgPolizaCantidadCuota",
    	        			cls: "number-field",
    	        			hideTrigger: true,
    	        			allowDecimals: false,
    	        			allowBlank: false,
    	        			maxLength: 5,
    	        			value: 12,
    	        			defaultValue: 12,
    	        			width: 105,
    	        			colspan: 1
    	        		},
    	        		{xtype: "label", text: "Fecha Vigencia:", cls: "x-form-item", colspan: 1, width: 105},
    	        		{xtype: "label", text: "Fecha Renovaci\u00F3n:", cls: "x-form-item", width: 105, colspan: 1},
    	        		{xtype: "hidden"},
    	        		{
    	        			xtype: "datefield",
    	        			name: "asgPoliza.asgPolizaFechaInicio",
    	        			allowBlank: false,
    	        			submitFormat: "Ymd",
    	        			width: 100,
    	        			colspan: 1
    	        		},{
    	        			xtype: "datefield",
    	        			name: "asgPoliza.asgPolizaFechaFinalizacion",
    	        			allowBlank: false,
    	        			submitFormat: "Ymd",
    	        			width: 105,
    	        			colspan: 1
    	        		}
        	        ]
	        	},
				buttons: [
		          {
		        	  text: "Renovar Poliza",
		        	  handler: AsgDetalleRenovacion.confirmRenovacion
		          },{
		        	  text: "Cerrar",
		        	  handler: function(){
		        		  Ext.WindowMgr.get("asgDetalleRenovacionWindow").hide();
		        	  }
		          }
	            ]
			}).show();
		},
		initConfig: function(config){
			if(!config) config = {};
			Ext.define("asgDetallePolizaModel", {
			    extend: "Ext.data.Model",
			    fields: [
		             "asgClienteId", "asgPolizaId",
			         "asgCliente", "asgPolizaNumero", "asgPolizaAseguradora", 
			         "asgPolizaTipoSeguro", "asgPolizaAsesor",
			         "asgPolizaFechaInicio", "asgPolizaFechaFinalizacion",
			         "asgPolizaAseguradoraId", 
			         "asgPolizaTipoSeguroId", "asgPolizaAsesorId", "asgPolizaPlanId",
			         "vencida"
		        ]
			});
			var asgDetallePolizaStore = Ext.create("Ext.data.Store", {
				autoLoad: true,
				pageSize: Asg.constants.PAGE_SIZE,
				model: "asgDetallePolizaModel",
				proxy: {
			        type: "ajax",
			        url: Asg.constants.CONTEXT_PATH + "/renovaciones/doSearch",
			        reader: {
			        	type: "array",
			        	root: "list",
			        	totalProperty: "totalResult"
	        		}
			    },
			    listeners: {
			    	beforeload: function(store, operation, options){
			    		if(!operation) operation = {};
			    		if(!operation.params) operation.params = {};
			    		var form = Ext.getCmp("asgDetallePolizaForm").getForm();
			    		if(!form.isValid()){
			    			Asg.Message.alertInvalidFields();
			    			return false;
			    		}
			    		var values = form.getValues();
			    		for(value in values){
			    			operation.params["asgSeguroForm." + value] = values[value];
			    		}
			    		if(operation.params.restart){
			    			operation.start = 0;
			    			operation.page = 1;
			    		}
			    	}
			    	
			    },
			    groupers: [{property: "asgCliente"}]
			});
			return {
				menu: [
			       {
	                	xtype: "buttongroup",
	                	title: "POLIZAS",
	                	defaults: {iconAlign: "left"},
	                	padding:"5 5 5 5",
	                	style: "min-width: 200px;",
			            bodyStyle:"min-height:25px",
	                	items: [
                	        {
                	        	text: "Renovar", 
                	        	iconCls: Asg.constants.SAVE_ICON,
                	        	hidden: config.isReadOnly,
                	        	handler: function(){
                	        		AsgDetalleRenovacion.showWindow(config);
                	        	}
                	        },
                	        {xtype: 'tbspacer', maxWidth: 5, minWidth: 5, width: 5},
	            	        {text: "Ver Datos", iconCls: Asg.constants.OPEN_ICON, handler:Commons.openPoliza},
	    			        {xtype: 'tbspacer', maxWidth: 5, minWidth: 5, width: 5},
	            	        {text: "Cancelar Poliza", iconCls: Asg.constants.CANCEL_ICON, handler:AsgDetalleRenovacion.confirmCancelacion, hidden: config.isReadOnly},
	            	        {xtype: 'tbspacer', maxWidth: 5, minWidth: 5, width: 5}
	    	            ]
	                },
	                "->",
	                Viewport.getMenuHome()
                ],
				items: [ 
			        {
			        	xtype: "form",
			        	id: "asgDetallePolizaForm",
			        	height: 125,
			        	bodyStyle: "background: #DFE8F6",
			        	layout: "fit",
			        	border: false,
						items: {
							xtype: "fieldset",
							title: "PARAMETROS DE BUSQUEDA",
							style: "background: #FFFFFF;",
							layout: {
	        	        		type: "table",
								columns: 3,
								tableAttrs: {
						            style: {width: "500px"},
						            align: "center"
								}
	        	        	},
	        	        	defaults: Asg.Form.defaults({width: 230, labelAlign: "top"}),
	        	        	items: [
	    	        	        {
	    	        	        	xtype: "textfield",
	    	        	        	id: "asgPolizaNumero",
	    	        	        	name: "asgPolizaNumero",
	    	        	        	fieldLabel: "No. Poliza",
	    	        	        	width: 110
	    	        	        },{
	    	        	        	xtype: "datefield",
	    	        	        	id: "asgFechaFinalizacion1",
	    	        	        	name: "asgFechaFinalizacion1",
	    	        	        	fieldLabel: "Fecha Renovaci\u00F3n",
	    	        	        	width: 110,
	    	        	        	submitFormat: "Ymd",
	    	        	        	allowBlank: false,
	    	        	        	value: config.asgFechaFinalizacion1
	    	        	        },{
	    	        	        	xtype: "datefield",
	    	        	        	id: "asgFechaFinalizacion2",
	    	        	        	name: "asgFechaFinalizacion2",
	    	        	        	fieldLabel: " ",
	    	        	        	labelSeparator: "&nbsp;",
	    	        	        	width: 105,
	    	        	        	submitFormat: "Ymd",
	    	        	        	allowBlank: false,
	    	        	        	value: config.asgFechaFinalizacion2
	    	        	        },{
	    	        	        	xtype: "textfield",
	    	        	        	id: "asgClienteNombreCompleto",
	    	        	        	name: "asgClienteNombreCompleto",
	    	        	        	fieldLabel: "Cliente / Raz\u00F3n Social / Nombre Comercial",
	    	        	        	width: 445,
	    	        	        	colspan: 3
	    	        	        }
		        	        ]
						}
			        },{
			        	xtype: "grid",
			        	id: "asgDetalleRenovacionGrid",
			        	flex: 1,
			        	frame: true,
			        	minHeight: 300,
			        	margins: "5 0 0 0",
			        	store: asgDetallePolizaStore,
			        	columns: [
	        	           {dataIndex: "vencida", width: 30, renderer: AsgDetalleRenovacion.rendererVencimiento},
	        	           {header: "No. Poliza", dataIndex: "asgPolizaNumero", width: 140},
	        	           {header: "Tipo de Seguro", dataIndex: "asgPolizaTipoSeguro", width: 160},
	        	           {header: "Aseguradora", dataIndex: "asgPolizaAseguradora", flex: 1, minWidth: 150},
	        	           {header: "Asesor", dataIndex: "asgPolizaAsesor", flex: 1, minWidth: 225},
	        	           {header: "Fecha Vigencia", dataIndex: "asgPolizaFechaInicio", width: 100, renderer: "webFormatDateYmd_d_m_Y"},
	        	           {header: "Fecha Renovaci\u00F3n", dataIndex: "asgPolizaFechaFinalizacion", width: 110, renderer: "webFormatDateYmd_d_m_Y"}
        	            ],
        	            selModel:{
	        	            listeners: {
	        	            	selectionchange: function(selectionModel, rows){
	        	            		if(rows && rows.length > 0){
	        	            			AsgSeguros.setAsgClienteId(rows[0].get("asgClienteId"));
	        	            			AsgSeguros.setAsgPolizaId(rows[0].get("asgPolizaId"));
	        	            		}
	        	            	}
	        	            }
        	            },
        	            features: [
				           {
				        	   ftype: "grouping",
				        	   enableNoGroups: false,
				        	   groupHeaderTpl: '{name} -> {rows.length} Poliza{[values.rows.length > 1 ? "s" : ""]}'
				           }
			            ],
	                    dockedItems: [
                           {
                        	   xtype: "toolbar",
                        	   dock: "top",
                        	   items: [
                    	           "->",
                    	           {
                    	        	   text: "Buscar", 
                    	        	   iconCls: Asg.constants.SEARCH_ICON,
                    	        	   handler: function(){
                    	        		   asgDetallePolizaStore.currentPage = 1;
                    	        		   asgDetallePolizaStore.load({params:{restart: true}});
                    	        		   AsgSeguros.setAsgClienteId(null);
                    	        		   AsgSeguros.setAsgPolizaId(null);
                    	        	   }
                	        	   },{
                    	        	   text: "Borrar Filtros", 
                    	        	   iconCls: Asg.constants.CANCEL_ICON,
                    	        	   handler: function(){
                    	        		   Ext.getCmp("asgDetallePolizaForm").getForm().reset();
                    	        	   }
                	        	   }
                	           ]
                           },{
                        	   xtype: "pagingtoolbar",
                        	   store: asgDetallePolizaStore,
                        	   dock: "bottom",
                        	   displayInfo: true
			               }
                        ]
			        }
				]
			};
		}			
	};
}();